import 'dart:io';

import 'package:ladder_cash/app/app.dart';
import 'package:ladder_cash/app/com/http/http_request.dart';
import 'package:ladder_cash/app/com/plugin/device_data_plugin.dart';
import 'package:flutter/services.dart';
import 'package:liuxlcommon/util/string_utils.dart';
import 'package:ladder_cash/app/key_mix.dart';

import '../../../library/src/logger.dart';

class CommonPlugin {
  static const MethodChannel _channel = MethodChannel('CommomPlugin');

  static get goToRate async {
    return await _channel.invokeMethod("goToRate");
  }

  static get toNearbyBanks async {
    return await _channel.invokeMethod("toNearbyBanks");
  }

  static void initFB(dynamic data) async {
    var newData = data['facebook'.hx];
    return await _channel.invokeMethod("initFB", {
      "appID": newData['appID'.hx],
      "appName": newData['facebookDisplayName'.hx],
      "clientToken": newData['facebookClientToken'.hx],
      "urlScheme": newData['cfBundleURLScheme'.hx],
    });
  }

  static bool isAdjust = false;

  static get initAdjust async {

    bool openatt = false;
    if (Platform.isIOS) {
      openatt = await CommonPlugin.openATT;
    }
    // if (isAdjust) return;
    var discernment = await DeviceDataPlugin.getIdfa;
    if (discernment.toString().contains("00000000") && openatt) {
      //没有获取到，但是 又返回的是 true ，应该是没有弹窗，
      isAdjust = false;
    //  return; //自要是 允许都是可以拿到的
    } else {
      //获取成功防止重复提交
      isAdjust = true;
    }
    var data = await HttpRequest().post(
        '/v3/loan-confirm/google-market-ios-new'.hx,
        {
          'idfv'.hx: await DeviceDataPlugin.getIdfv,
          'idfa'.hx: discernment
        },
        autoToast: false);
    if (data != null) {
      if (StringUtils.isNotEmpty(data['afKey'.hx])) {
        isAdjust = true;
        // bool b = await _channel.invokeMethod("initAdjust", {"YourAppToken": data['afKey'.hx]});
        return isAdjust;
      }
    } else {
      isAdjust = false;
    }
    return false;
  }

  static get openATT async => await _channel.invokeMethod("openATT");

  static get getFacePath async {
    return await _channel
        .invokeMethod("GetFacePath", {"language": App.localeCode});
  }

  static Future<String> getWaitIdea() async {
    var status = await openATT;
    if (status) {
      String idfa = await DeviceDataPlugin.getIdfa;
      if (idfa.contains("000000000000")) {
        //不确定，可能没有弹窗,等待一秒 继续
        await Future.delayed(const Duration(seconds: 1));
        return await getWaitIdea();
      } else {
        return idfa;
      }
    } else {
      //被拒绝 ，直接返回
      return await DeviceDataPlugin.getIdfa;
    }
  }
}
